import baseController from "./controller"
class workflowController extends baseController {

    save (postModel = this.context.models, isSend = false, url, showMsg, msgTitle,isBack=true) {
        if(showMsg==null||showMsg==undefined) {
            showMsg=true
        }
        if (!url) {
            url = this.appendPrimaryKey(isSend ? this.context.urls.processRun : this.context.urls.processSave)
        }

        if (postModel == undefined || url == undefined) {
            this.afterSave(false, {
                message: 'PostModel或者URL不可为undefined'
            });
        } else {
            if (!this.validate()) {
                this.$f7.dialog.toast('请按提示填写必填项');
                return;
            }
            postModel = _.cloneDeep(postModel);


            if (this.onBeforeSave(postModel) === false) {
                return;
            }
            if (isSend && this.onBeforeSend(postModel) === false) {
                return;
            }
            url = this.appendWorkflowArgs(url);
            postModel.pageAction = this.context.pageAction;
            if (isSend) {
                postModel.workflowComment = this.context.selectUser.comment;
                postModel.choice = {
                    tran: this.context.selectUser.tran,
                    activity: this.context.selectUser.activity,
                    users: this.context.selectUser.users.join(",").replace(new RegExp(this.context.selectUser.tran + "\\$", 'gm'), ""),
                };
                if (this.context.controlData.workflow.needChoose) {
                    if (!postModel.choice.users) {
                        this.$f7.dialog.alert("请选择处理人");
                        return;
                    }
                    if (!postModel.choice.tran || !postModel.choice.activity) {
                        this.$f7.dialog.alert("请选择处理环节");
                        return;
                    }
                }
                // if(!postModel.workflowComment&&!this.context.controlData.workflow.isFirstTask){
                //     this.$f7.dialog.alert("请填写处理意见");
                //     return;
                // }

            }

            this.$f7.preloader.show();
            this.$f7.request.postJSON(url, postModel, (r) => {
                this.$f7.preloader.hide();
                if (isSend) {
                    this.onAfterSend(r.success, r)
                } else {
                    _.extend(this.context.models.model, r.parameters.model)
                }
                this.afterSave(r.success, r, isSend,showMsg,msgTitle,isBack);
            }, (r) => {
                this.$f7.preloader.hide();
                if (isSend) {
                    this.onAfterSend(false, r)
                }
                this.afterSave(false, r, isSend,showMsg,msgTitle,isBack);
            });
        }

    }
    async send (el,isBack) {
        if (!this.context.controlData.workflow.needChoose) {
            this.save(this.context.models, true,null,true,null,isBack);
        } else {
            let selectUser = this.appendWorkflowArgs(this.context.urls.selectUser)
            let tmpChoice = await this.getPromise(selectUser, this.context.models);
            this.context.choicesOptions = this._buildChoices(tmpChoice);

            this.context.commentOptions = await this.getPromise("/workflow/actExtCommonComment/loadMyComment", {});

            //    if(this.context.choicesOptions.length>0||this.context.commentOptions.length>0){
            this.$f7.popup.open("." + el);
            // if (this.context.choicesOptions && this.context.choicesOptions.length > 0) {
            //     _.forEach(this.context.choicesOptions, item => {
            //         if (item.text == '营运单位确认' || item.id == 'toLeader') {
            //             this.context.selectUser.tran = item.id;
            //         }
            //     })
            // }
            //    }

        }
    }
    afterSave (isSuccess, result, isSend,showMsg,msgTitle,isBack) {
        let msg
        if (isSuccess) {
            if (result.parameters && (result.parameters.keys||result.parameters.formId) && this.context.pageAction == 'create') {
                let key={}
                if(result.parameters.formId&&result.parameters.formKeyName){
                    key[result.parameters.formKeyName]=result.parameters.formId
                }
                this.context.pageAction = "edit";
                this.context.models.pageAction = "edit";
                this.context.pageActionText = "编辑";
                this.context.controlData.workflow.taskId = result.parameters.taskId;
                this.context.controlData.workflow.instanceId = result.parameters.instanceId;
                this.context.primaryKey = result.parameters.keys||key;
            }
            msg = result.message || msgTitle ||(isSend ? '发送成功' : '保存成功');
            if (result.parameters.nextHandlers) {
                let nestHandler = result.parameters.nextHandlers.join(",");
                if (nestHandler)
                    msg += "下一环节处理人：<br />" + nestHandler;
            }
            if(showMsg){
                this.$f7.dialog.alert(msg, () => {
                    if (isSend&&isBack) {
                        this.$f7.popup.close();
                        this.$f7.views.current.router.back({force:true});
                    }
                    this.onAfterSave(isSuccess, result);
                });
            }
        } else {
            if(showMsg){
                msg = result.message || msgTitle || (isSend ? "发送失败" : "保存失败");
                this.$f7.dialog.alert(msg, () => {
                    this.onAfterSave(isSuccess, result);
                });
            }
        }
    }
    onBeforeSend (postModel) {
        return true;
    }
    onAfterSend (isSuccess, result) {

    }
    appendWorkflowArgs (url) {
        var args = {
            appCode: this.context.controlData.workflow.appCode,
            version: this.context.controlData.workflow.version,
            taskId: this.context.controlData.workflow.taskId,
            pageAction: this.context.pageAction
        };
        for (var o in args) {
            if (!args[o]) continue;
            var joinChar = url.indexOf("?") == -1 ? "?" : "&";
            url += joinChar;
            url += o + "=" + args[o];
        }
        return url;
    }

    /** 撤回 */
    fnRollback (postParam, fnCallback) {
        let url = this.appendWorkflowArgs(this.context.urls.processRollback);
        url = this.appendPrimaryKey(url);
        url += "&historyTaskId=" + this.context.controlData.workflow.historyTaskId;
        postParam = postParam || {};
        postParam.pageAction = "view";
        this.$util.getPromise(url, postParam).then(res => {
            this.$util.isFunction(fnCallback) && fnCallback(res);
        });
    }

    /** 退回 */
    fnBackward (workflowComment, fnCallback, failCallback) {
        let url = this.appendWorkflowArgs(this.context.urls.processBackward);
        url = this.appendPrimaryKey(url);
        let postParam = { 
            workflowComment: workflowComment, 
            pageAction: this.context.pageAction,
        };
        this.$util.getPromise(url, postParam).then(res => {
            this.$util.isFunction(fnCallback) && fnCallback(res);
        }).catch(e=>{
            this.$util.isFunction(failCallback) && fnCallback(e);
        })
    }

    /** 退回 */
    fnBackJump (workflowComment, fnCallback, failCallback,usertask="usertask2" ,extParams = {}) {
        let url = this.context.urls.processJump;
        // url = this.appendPrimaryKey(url);
        let handlerId="";
        let arr=[]
        if(this.context.controlData.workflow.history.length>0){
          this.context.controlData.workflow.history.forEach(item=>{
            if(item.taskCode==usertask&&item.handlerId&&arr.indexOf(item.handlerId)==-1){
              arr.push(item.handlerId)
            }
          })
        }
        if(arr.length>0) handlerId=arr.toString()
        let postParam = { 
            workflowComment: workflowComment,
            taskId:this.context.controlData.workflow.taskId,
            handlerId,
            targetActivityId:usertask,
            appCode:this.context.controlData.workflow.appCode,
            isUserId:1,
            pageAction:'edit',
            ...this.context.primaryKey,
            ...extParams
        };
        this.$util.getPromise(url, postParam).then(res => {
            this.$util.isFunction(fnCallback) && fnCallback(res);
        }).catch(e=>{
            this.$util.isFunction(failCallback) && fnCallback(e);
        })
    }
    
    _buildChoices (source) {
        let _this = this;
        let result = [];
        _.forEach(source, function (t, i) {
            if (t.type == "dept") {
                _.forEach(t.children || [], function (t2, i2) {
                    t2.text = "{0}({1})".format(t2.text, t.text);
                    result.push(t2);
                });
            } else {
                t.children = _this._buildChoices(t.children || []);
                result.push(t);
            }
        });
        return result;
    }
    getPromise (url, params) {
        let _this = this;
        return new Promise((rs, rj) => {
            _this.$f7.request.post(
                url,
                params,
                rlt => {
                    if (typeof rlt == 'string') {
                        rlt = JSON.parse(rlt)
                    }
                    rs(rlt);
                },
                rlt => {
                    rlt.message = "获取数据失败，请稍后重试";
                    rj(rlt);
                }
            );
        });
    }

}
export default workflowController;
